package com.netflix;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@SpringBootApplication
public class SpringcloudNetflixEurekaConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringcloudNetflixEurekaConsumerApplication.class, args);
    }

    @Configuration
    public class restTemplateConfiguration{
        @Bean
        public RestTemplate restTemplate(){
            return new RestTemplate();
        }
    }

    @RestController
    static class testController{
        @Resource
        private RestTemplate restTemplate;
        @Resource
        private DiscoveryClient discoveryClient;
        @Resource
        private LoadBalancerClient loadBalancerClient;

        @RequestMapping("/hello")
        public String hello(String name){
            List<ServiceInstance> instances = discoveryClient.getInstances("demo-provider");
            ServiceInstance instance=instances.size()>0?instances.get(0):null;
            if(instance==null) {
                instance = loadBalancerClient.choose("demo-provider");
            }
            if(instance==null){
                throw  new IllegalStateException("获取不到实列");
            }
            String targetUrl=instance.getUri()+"/test?name="+name;
            String response=restTemplate.getForObject(targetUrl,String.class);
            return "consumer:"+response;

        }
    }

}
